package com.dfbz.controller.user;

import com.dfbz.controller.BaseServlet;
import com.dfbz.model.Article;
import com.dfbz.model.Dept;
import com.dfbz.model.Userfocus;
import com.dfbz.pojo.PageEntity;
import com.dfbz.model.User;
import com.dfbz.service.ArticleService;
import com.dfbz.service.DeptService;
import com.dfbz.service.UserService;
import com.dfbz.service.UserfocusService;
import com.dfbz.service.impl.ArticleServiceImpl;
import com.dfbz.service.impl.DeptServiceImpl;
import com.dfbz.service.impl.UserServiceImpl;
import com.dfbz.service.impl.UserfocusServiceImpl;
import com.dfbz.utils.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    UserService userService=new UserServiceImpl();
    DeptService deptService=new DeptServiceImpl();
    UserfocusService userfocusService=new UserfocusServiceImpl();
    ArticleService articleService=new ArticleServiceImpl();
    public void findPage(HttpServletRequest req, HttpServletResponse resp){
        try {
            String p = req.getParameter("currPage");
            String realName=req.getParameter("realName");
            Integer currPage;
            if (p == null){
                currPage=1;
            }
            else {
                currPage=Integer.parseInt(p);
            }
            if (realName == null){
                if (null !=req.getSession().getAttribute("realName")){
                    realName=(String) req.getSession().getAttribute("realName");
                }
                else {
                    realName="";
                }
            }
            ArrayList<Userfocus> focuss = userfocusService.findList();
            ArrayList<Integer> focs = new ArrayList<>();
            User userInfo = (User) req.getSession().getAttribute("userInfo");
            for (Userfocus userfocus:focuss) {
                if (userfocus.getUserId()==userInfo.getId()){
                    focs.add(userfocus.getUserFocusId());
                }
            }
            req.getSession().setAttribute("focs",focs);
            req.getSession().setAttribute("realName",realName);
            PageEntity<User> pageEntity = userService.findPage(currPage, realName);
            req.getSession().setAttribute("pageEntity",pageEntity);
            req.getRequestDispatcher("/view/location/user").forward(req,resp);
            return;
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void back(HttpServletRequest req, HttpServletResponse resp){
        PageEntity<User> pageEntity = (PageEntity<User>) req.getSession().getAttribute("pageEntity");
        String realName =(String) req.getSession().getAttribute("realName");
        Integer currPage = pageEntity.getCurrPage();
        Integer begin = pageEntity.getBegin();
        try {
            if (begin==currPage){
                if (currPage==1){
                    req.getRequestDispatcher("/view/location/user").forward(req,resp);
                    return;
                }
                else {
                    currPage-=1;
                    PageEntity<User> page = userService.findPage(currPage, realName);
                    req.getSession().setAttribute("pageEntity",page);
                    req.getRequestDispatcher("/view/location/user").forward(req,resp);
                    return;
                }
            }
            else {
                currPage-=1;
                PageEntity<User> page = userService.findPage(currPage, realName);
                req.getSession().setAttribute("pageEntity",page);
                req.getRequestDispatcher("/view/location/user").forward(req,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void next(HttpServletRequest req, HttpServletResponse resp){
        PageEntity<User> pageEntity = (PageEntity<User>) req.getSession().getAttribute("pageEntity");
        String realName =(String) req.getSession().getAttribute("realName");
        Integer currPage = pageEntity.getCurrPage();
        Integer end = pageEntity.getEnd();
        Integer totalPage = pageEntity.getTotalPage();
        try {
            if (currPage==end){
                if (currPage==totalPage){
                    req.getRequestDispatcher("/view/location/user").forward(req,resp);
                    return;
                }
                else {
                    currPage+=1;
                    PageEntity<User> page = userService.findPage(currPage, realName);
                    req.getSession().setAttribute("pageEntity",page);
                    req.getRequestDispatcher("/view/location/user").forward(req,resp);
                    return;
                }
            }
            else {
                currPage+=1;
                PageEntity<User> page = userService.findPage(currPage, realName);
                req.getSession().setAttribute("pageEntity",page);
                req.getRequestDispatcher("/view/location/user").forward(req,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //个人中心
    public void user_look(HttpServletRequest req, HttpServletResponse resp){
        try {
            User userInfo =(User) req.getSession().getAttribute("userInfo");
            User newUserInfo = userService.findByName(userInfo.getUsername());
            ArrayList<Dept> depts = deptService.findList();
            ArrayList<Userfocus> userfocuss = userfocusService.findList();
            Integer focusCount=0;
            String userDeptName=null;
            for (Userfocus userfocus:userfocuss) {
                if (userfocus.getUserId() == userInfo.getId()){
                    focusCount +=1;
                }
            }
            for (Dept dept:depts) {
                if (dept.getId() == userInfo.getDeptId()){
                    userDeptName=dept.getName();
                }
            }
            req.getSession().setAttribute("userInfo",newUserInfo);
            req.getSession().setAttribute("userDeptName",userDeptName);
            req.getSession().setAttribute("focusCount",focusCount);
            req.getSession().setAttribute("deptList",depts);
            req.getRequestDispatcher("/view/location/user_look").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void updateDetail(HttpServletRequest req, HttpServletResponse resp){
        try {
            User userInfo = (User) req.getSession().getAttribute("userInfo");
            Integer id=userInfo.getId();
            String real_name=req.getParameter("real_name");
            String phone=req.getParameter("phone");
            Integer age=Integer.parseInt(req.getParameter("age"));
            String gender=req.getParameter("gender");
            String is_secret=req.getParameter("is_secret");
            if (is_secret ==null){
                is_secret="0";
            }
            User user=new User();
            user.setId(id);
            user.setRealName(real_name);
            user.setPhone(phone);
            user.setAge(age);
            user.setGender(gender);
            user.setIsSecret(is_secret);
            userService.update(user);
            req.getRequestDispatcher("/user/user_look").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //图片上传
    public void uploadImg(HttpServletRequest req, HttpServletResponse resp){
        try {
            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = fileUpload.parseRequest(req);
            if (items.size() >0){
                FileItem item = items.get(0);
                int index = item.getName().lastIndexOf("\\.");
                String suffix;
                if (-1 != index){
                    suffix = item.getName().substring(index + 1);
                }
                else {
                    suffix="jpg";
                }
                String fileName= StrUtil.getUUID()+"."+suffix;
                File file = new File("E:\\xbjy-img\\"+fileName);
                item.write(file);
                //更新用户头像
                String path="/upload/"+fileName;
                User userInfo = (User) req.getSession().getAttribute("userInfo");
                Integer id = userInfo.getId();
                userService.updateImg(id,path);
                userInfo.setPic(path);
                req.getSession().setAttribute("userInfo",userInfo);
                resp.getWriter().write(path);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //用户信息详情
    public void user_detail(HttpServletRequest req, HttpServletResponse resp){
        try {
            ArrayList<Dept> depts = deptService.findList();
            ArrayList<Userfocus> focuss = userfocusService.findList();
            Integer uId = Integer.parseInt(req.getParameter("uId"));
            User userInfo = (User) req.getSession().getAttribute("userInfo");
            if (uId == userInfo.getId()){
                String look_userDeptName=null;
                Integer look_focusCount=0;
                for (Userfocus userfocus:focuss) {
                    if (userfocus.getUserId() == userInfo.getId()){
                        look_focusCount +=1;
                    }
                }
                for (Dept dept:depts) {
                    if (dept.getId() == userInfo.getDeptId()){
                        look_userDeptName=dept.getName();
                    }
                }
                req.getSession().setAttribute("look_user",userInfo);
                req.getSession().setAttribute("look_userDeptName",look_userDeptName);
                req.getSession().setAttribute("look_focusCount",look_focusCount);
                req.getRequestDispatcher("/view/location/user_detail").forward(req,resp);
            }
            else {
                //查看数+1
                userService.updateLook(uId);
                User look_user = userService.findById(uId);
                Integer look_focusCount=0;
                String look_userDeptName=null;
                for (Userfocus userfocus:focuss) {
                    if (userfocus.getUserId() == look_user.getId()){
                        look_focusCount +=1;
                    }
                }
                for (Dept dept:depts) {
                    if (dept.getId() == look_user.getDeptId()){
                        look_userDeptName=dept.getName();
                    }
                }
                req.getSession().setAttribute("look_user",look_user);
                req.getSession().setAttribute("look_userDeptName",look_userDeptName);
                req.getSession().setAttribute("look_focusCount",look_focusCount);
                req.getRequestDispatcher("/view/location/user_detail").forward(req,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //关注
    public void focus(HttpServletRequest req, HttpServletResponse resp){
        try {
            Integer fid=Integer.parseInt(req.getParameter("fid"));
            User userInfo = (User) req.getSession().getAttribute("userInfo");
            String data=null;
            if (fid==userInfo.getId()){
                //不能关注自己
                data="me";

            }
            else {
                ArrayList<Userfocus> focuss = userfocusService.findList();
                Integer index=0;
                for (Userfocus userfocus:focuss) {
                    if (userfocus.getUserId()==userInfo.getId()
                            &&userfocus.getUserFocusId()==fid){
                        index=1;
                        break;
                    }
                }
                if (index==1){
                    //已关注--删除
                    data="no";
                    userfocusService.deleteFocus(userInfo.getId(),fid);
                }
                else {
                    //未关注--添加
                    data="yes";
                    Userfocus userfocus=new Userfocus();
                    userfocus.setUserId(userInfo.getId());
                    userfocus.setUserFocusId(fid);
                    userfocusService.save(userfocus);
                }
            }
            resp.getWriter().write(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //我关注的用户
    public void my_user(HttpServletRequest req, HttpServletResponse resp){
        try {
            User userInfo = (User) req.getSession().getAttribute("userInfo");
            String p=req.getParameter("currPage");
            Integer currPage;
            if (p==null){
                currPage=1;
            }
            else {
                currPage=Integer.parseInt(p);
            }
            PageEntity<User> focusPageEntity = userService.findfocusAll(currPage,userInfo.getId());
            req.getSession().setAttribute("focusPageEntity",focusPageEntity);
            req.getRequestDispatcher("/view/location/my_user").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void my_user_next(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        User userInfo = (User) session.getAttribute("userInfo");
        PageEntity<User> focusPageEntity = (PageEntity<User>)session.getAttribute("focusPageEntity");
        Integer currPage = focusPageEntity.getCurrPage();
        Integer end = focusPageEntity.getEnd();
        Integer totalPage = focusPageEntity.getTotalPage();
        try {
            if (currPage==end){
                if (currPage==totalPage){
                    req.getRequestDispatcher("/view/location/my_user").forward(req,resp);
                    return;
                }
                else {
                    currPage+=1;
                    PageEntity<User> pageEntity = userService.findfocusAll(currPage, userInfo.getId());
                    session.setAttribute("focusPageEntity",pageEntity);
                    req.getRequestDispatcher("/view/location/my_user").forward(req,resp);
                }
            }
            else {
                currPage+=1;
                PageEntity<User> pageEntity = userService.findfocusAll(currPage, userInfo.getId());
                session.setAttribute("focusPageEntity",pageEntity);
                req.getRequestDispatcher("/view/location/my_user").forward(req,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void my_user_back(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        User userInfo = (User) session.getAttribute("userInfo");
        PageEntity<User> focusPageEntity = (PageEntity<User>)session.getAttribute("focusPageEntity");
        Integer currPage = focusPageEntity.getCurrPage();
        Integer begin = focusPageEntity.getBegin();
        try {
            if (currPage==begin){
                if (currPage==1){
                    req.getRequestDispatcher("/view/location/my_user").forward(req,resp);
                    return;
                }
                else {
                    currPage-=1;
                    PageEntity<User> pageEntity = userService.findfocusAll(currPage, userInfo.getId());
                    session.setAttribute("focusPageEntity",pageEntity);
                    req.getRequestDispatcher("/view/location/my_user").forward(req,resp);
                }
            }
            else {
                currPage-=1;
                PageEntity<User> pageEntity = userService.findfocusAll(currPage, userInfo.getId());
                session.setAttribute("focusPageEntity",pageEntity);
                req.getRequestDispatcher("/view/location/my_user").forward(req,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //关注列表取消关注
    public void unfocus(HttpServletRequest req, HttpServletResponse resp){
        try {
            HttpSession session = req.getSession();
            PageEntity<User> focusPageEntity = (PageEntity<User>)session.getAttribute("focusPageEntity");
            Integer currPage = focusPageEntity.getCurrPage();
            Integer fid=Integer.parseInt(req.getParameter("fid"));
            User userInfo = (User) req.getSession().getAttribute("userInfo");
            userfocusService.deleteFocus(userInfo.getId(),fid);
            PageEntity<User> pageEntity = userService.findfocusAll(currPage, userInfo.getId());
            req.getSession().setAttribute("focusPageEntity",pageEntity);
            req.getRequestDispatcher("/view/location/my_user").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //收藏的文章
    public void article_collect(HttpServletRequest req, HttpServletResponse resp){
        try {
            HttpSession session = req.getSession();
            User userInfo =(User) session.getAttribute("userInfo");
            String p=req.getParameter("colCurrPage");
            String collect_title=req.getParameter("collect_title");
            Integer currPage;
            if (p==null){
                currPage=1;
            }
            else {
                currPage=Integer.parseInt(p);
            }
            if (collect_title==null){
                if (null !=session.getAttribute("collect_title")){
                    collect_title=(String) session.getAttribute("collect_title");
                }
                else {
                    collect_title="";
                }
            }
            session.setAttribute("collect_title",collect_title);
            PageEntity<Article> collectPageEntity = articleService.findCollectPage(userInfo.getId(), currPage, collect_title);
            session.setAttribute("collectPageEntity",collectPageEntity);
            req.getRequestDispatcher("/view/location/article_collect").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void colArt_next(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        User userInfo = (User) session.getAttribute("userInfo");
        PageEntity<Article> collectPageEntity = (PageEntity<Article>) session.getAttribute("collectPageEntity");
        String collect_title = (String) session.getAttribute("collect_title");
        Integer currPage = collectPageEntity.getCurrPage();
        Integer end = collectPageEntity.getEnd();
        Integer totalPage = collectPageEntity.getTotalPage();
        try {
            if (currPage==end){
                if (currPage==totalPage){
                    req.getRequestDispatcher("/view/location/article_collect").forward(req,resp);
                    return;
                }
                else {
                    currPage+=1;
                    PageEntity<Article> colPageEntity = articleService.findCollectPage(userInfo.getId(), currPage, collect_title);
                    session.setAttribute("collectPageEntity",colPageEntity);
                    req.getRequestDispatcher("/view/location/article_collect").forward(req,resp);
                    return;
                }
            }
            else {
                currPage+=1;
                PageEntity<Article> colPageEntity = articleService.findCollectPage(userInfo.getId(), currPage, collect_title);
                session.setAttribute("collectPageEntity",colPageEntity);
                req.getRequestDispatcher("/view/location/article_collect").forward(req,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void colArt_back(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        User userInfo = (User) session.getAttribute("userInfo");
        PageEntity<Article> collectPageEntity = (PageEntity<Article>) session.getAttribute("collectPageEntity");
        String collect_title = (String) session.getAttribute("collect_title");
        Integer currPage = collectPageEntity.getCurrPage();
        Integer begin = collectPageEntity.getBegin();
        try {
            if (currPage==begin){
                if (currPage==1){
                    req.getRequestDispatcher("/view/location/article_collect").forward(req,resp);
                    return;
                }
                else {
                    currPage-=1;
                    PageEntity<Article> colPageEntity = articleService.findCollectPage(userInfo.getId(), currPage, collect_title);
                    session.setAttribute("collectPageEntity",colPageEntity);
                    req.getRequestDispatcher("/view/location/article_collect").forward(req,resp);
                    return;
                }
            }
            else {
                currPage-=1;
                PageEntity<Article> colPageEntity = articleService.findCollectPage(userInfo.getId(), currPage, collect_title);
                session.setAttribute("collectPageEntity",colPageEntity);
                req.getRequestDispatcher("/view/location/article_collect").forward(req,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
